<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <!-- <el-form :inline="true" size="medium">
            <el-form-item>
              <el-button type="primary" @click="showAddForm">新增</el-button>
            </el-form-item>
          </el-form> -->

          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item>
              <el-button type="primary" @click="search">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="序号"
        type="index"
        width="80">
      </el-table-column>
      <el-table-column
        prop="itemCode"
        label="任务编码"
        min-width="140">
      </el-table-column>
      <el-table-column
        prop="productTypeId1"
        label="申报类型"
        min-width="80">
        <template scope="scope">
          {{productTypeId(scope.row.productTypeId1,scope.row.productTypeId2)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="产品名称"
        min-width="80">
        <!-- <template scope="scope">

          {{nameModel(scope.row.name,scope.row.model)}}
        </template> -->
      </el-table-column>

      <el-table-column
        prop="model"
        label="产品型号"
        min-width="80">
        <!-- <template scope="scope">

          {{nameModel(scope.row.name,scope.row.model)}}
        </template> -->
      </el-table-column>
      <el-table-column
        prop="nickName"
        label="任务派发"
        min-width="80">
      </el-table-column>
      <el-table-column
        prop="userName"
        label="任务接收者"
        min-width="80">
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        min-width="50">
        <template scope="scope">
          {{statusDate(scope.row.status)}}
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="msg"
        label="信息"
        min-width="100">
      </el-table-column> -->
      <el-table-column
        prop="content"
        label="任务内容"
        min-width="100">
      </el-table-column>

      <el-table-column
        prop="createTime"
        label="任务下发时间"
        min-width="100">
        <template scope="scope">
          {{fmtDate(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="uploadingTime"
        label="上传时间"
        min-width="100">
        <template scope="scope">
          {{fmtDate(scope.row.uploadingTime)}}
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="picNum"
        label="照片数量"
        min-width="30">
      </el-table-column>
      <el-table-column
        prop="videoNum"
        label="视频数量"
        min-width="30">
      </el-table-column> -->
     <!-- <el-table-column
        prop="url"
        label="已上传任务"
        min-width="120">
        <template scope="scope"> -->
          <!-- {{urlData(scope.row.url)}} -->
         <!-- <el-image v-if="scope.row.fileType==1? true:false" :src="fileBaseUrl+url[0][0]" :preview-src-list="[fileBaseUrl+url[0][0]]" fit="contain" style="width: 120px;height: 120px;"></el-image>
          <video v-if="scope.row.fileType==2? true:false" width="250px" :src="fileBaseUrl+scope.row.url" alt="" controls="controls" >
            您的浏览器无法播放视频
          </video> -->
          <!-- <el-image v-if="item.type==1? true:false" :src="fileBaseUrl+item.url" :preview-src-list="[fileBaseUrl+item.url]" fit="contain" style="width: 120px;height: 120px;"></el-image>
          <video v-if="item.type==2? true:false" width="250px" :src="fileBaseUrl+item.url" alt="" controls="controls" >
            您的浏览器无法播放视频
          </video> -->
       <!-- </template>

      </el-table-column>
 -->


      <el-table-column
        prop="address"
        label="操作"
        min-width="160">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" v-if="scope.row.status==2?true:false"  @click="handleEdit(scope.$index, scope.row)">提交任务</el-button>
          <el-button size="mini" type="primary" v-if="scope.row.status==2?true:false"  @click="handleTaskChangeUser(scope.$index, scope.row)">转交</el-button>
          <!-- <el-button size="mini" type="primary" v-if="scope.row.status==3||scope.row.status==4?true:false"  @click="handleEdit(scope.$index, scope.row)">重新上传</el-button> -->
          <!-- <el-button size="mini" type="danger"   @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

     <el-dialog title="转交" :visible.sync="changeUserFormVisible" width="500px" :close-on-click-modal="false">
       <el-form :model="changeUserForm" ref="changeUserForm" >
         <el-form-item label="用户" label-width="100px">
           <el-select v-model="changeUserForm.userId" placeholder="请选择" style="width: 90%;" >
             <el-option
               v-for="item in userList"
               :key="item.id"
               :label="item.nickname"
               :value="item.id">
             </el-option>
           </el-select>
         </el-form-item>
       </el-form>
       <div slot="footer" class="dialog-footer">
         <el-button @click="changeUserFormVisible = false">取 消</el-button>
         <el-button type="primary" @click.native.prevent="submitChangeUser">转交</el-button>
       </div>
     </el-dialog>

    <el-dialog :title="editForm.status==2?'新增':'重新上传'" :visible.sync="editFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">


        <!-- <el-form-item label="车辆状态" label-width="100px">
          <el-input v-model="editForm.carStatus" autocomplete="off"></el-input>
        </el-form-item> -->

        <!-- 照片上传 -->
        <el-upload
          class="avatar-uploader"
          :action="uploadActionUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"

          multiple
          :on-success="handleAvatarSuccess"
          :file-list="fileList"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
        </el-upload>

        <el-upload
          class="avatar-uploader"
          :action="uploadActionUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemoveVideo"
          multiple
          :on-success="handleAvatarSuccessVideo"
          :file-list="fileVideoList"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传mp4/avi文件</div>
        </el-upload>

        <!-- <el-form-item label="照片" label-width="100px" prop="carImg2">
          <el-upload
            class="avatar-uploader"
            name="file"
            :action="uploadActionUrl"
            accept=".png,.jpeg,.jpg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload2"
            :on-error="handleAvatarError">
            <img v-if="editForm.carImg2" :src="fileBaseUrl+editForm.carImg2" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item> -->



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">{{ editForm.status==2?'提 交':'重新上传' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
import {getTestOrderTaskPvList,addTestOrderTaskPvList,updateTestOrderTaskPvList,getTestOrderTaskPvFileList,deleteTestOrderTaskPvList,TaskPVchangeUser} from "../../../api/test_order_task.js";

import {getToken} from '../../../common/utils/auth.js'
import {getTestCarList} from '../../../api/test_car.js'
import {getFileUrl} from '../../../api/file.js'
import {getAllUserList} from '../../../api/user.js'


export default {
  name: "testOrderTaskManage",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      editFormVisible:false,
      loading: false,
      fileList:[],
      fileVideoList:[],
      arrTemp:[],
      userList:'',
      url:[],

      editForm: {
        id: 0,
        tOrderId:'',
        picNum:'',
        status:'',
        tid:'',
        fileList:[],
        fileVideoList:[],
        videoNum:'',
        fileId:'',
      },
      editRules: {
        name: [{ required: true, message:"请输入收费项目", trigger: 'blur'}],
        price: [{ required: true, message:"请输入单价", trigger: 'blur'}],
        num: [{ required: true, message:"请输入数量", trigger: 'blur'}],
        unit: [{ required: true, message:"请输入单位", trigger: 'blur'}],
      },
      loadingDiv: null,
      searchForm: {
        name: '',
        price: '',
        unit:'',
      },
      TestWorkTypeList:{
        id: 0,
        name: '',
        price: '',
        unit:'',
      },
      TestCarName:{

      },
      testSiteList:[],
      carId:'',
      uploadActionUrl:'',
      changeUserFormVisible:false,
      changeUserForm:{
        id:'',
        userId:'',

      },
    }
  },
  computed:{

  },
  mounted() {
    let tOrderId=this.$route.params.tOrderId;
    this.tOrderId = tOrderId;

    this.init();

    this.getDataList(this.currentPage);

    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }

    let t = getToken();
    this.uploadActionUrl = this.$adminApiUrl + "/file/upload?_t="+t;
    this.fileBaseUrl = this.$adminApiUrl+"/file/get?_t="+t+"&f=";

  },
  methods: {
    getFileUrl(){

    },

    handleRemove(file, fileList) {

      this.fileList = fileList;
      let data = [];
      // console.log(this.fileList.length)
      for(var i=0;i<this.fileList.length;i++){

        // console.log(fileList[i].response.data)
        data.push(fileList[i].response.data)
      }
      this.editForm.fileList = data;
      // this.editForm.fileList = fileList;

            // console.log(file, fileList);
      },
      handleRemoveVideo(file, fileVideoList){
        this.fileVideoList = fileVideoList;
        let data = [];
        // console.log(this.fileList)
        for(var i=0;i<this.fileVideoList.length;i++){
          // console.log(fileList[i].response.data)
          data.push(fileVideoList[i].response.data)
        }
        this.editForm.fileVideoList = data;
      },

    handlePreview(file) {
            // console.log(file);
          },
    // beforeRemove(file, fileList) {
    //     return this.$confirm(`确定移除 ${ file.name }？`);
    //   },


    init(){



    },

    handleAvatarSuccess(res, file, fileList){
      // console.log("12")
      // this.avatarUploadLoadingDiv.close();
      if (res.code == 1){
        this.fileList = fileList;
        let data = [];
        // console.log(this.fileList.length)
        for(var i=0;i<this.fileList.length;i++){

          // console.log(fileList[i].response.data)
          if(fileList[i].response!=null&&fileList[i].response!=''){
            data.push(fileList[i].response.data)
          }
        }
        this.editForm.fileList = data;
        // console.log(this.editForm.fileList)
        // this.fileList = fileList;
        // console.log("++++++++++++++++++");
        // console.log(this.editForm.fileList);
        // console.log(this.res.data);
        // console.log("++++++++++++++++++");
        return;
      }else{
        this.$message({
          message: res.msg,
          type: 'warning'
        });
      }
    },
    handleAvatarSuccessVideo(res, file, fileVideoList){
      // this.avatarUploadLoadingDiv.close();
      if (res.code == 1){
        this.fileVideoList = fileVideoList;
        let data = [];
        // console.log(this.fileList)
        for(var i=0;i<this.fileVideoList.length;i++){
          // console.log(fileList[i].response.data)
          
          if(fileVideoList[i].response!=null&&fileVideoList[i].response!=''){
            data.push(fileVideoList[i].response.data)
          }
        }
        this.editForm.fileVideoList = data;
        // console.log(this.editForm.fileVideoList)
        // this.fileList = fileList;
        // console.log("++++++++++++++++++");
        // console.log(this.editForm.fileList);
        // console.log(this.res.data);
        // console.log("++++++++++++++++++");
        return;
      }else{
        this.$message({
          message: res.msg,
          type: 'warning'
        });
      }
    },
    beforeAvatarUpload1(){
      this.uploadKey='carImg1';
      this.avatarUploadLoadingDiv = util.showLoading("照片上传中");
    },
    beforeAvatarUpload2(){
      this.uploadKey='carImg2';
      this.avatarUploadLoadingDiv = util.showLoading("照片上传中");
    },
    beforeAvatarUpload3(){
      this.uploadKey='carImg3';
      this.avatarUploadLoadingDiv = util.showLoading("照片上传中");
    },

    handleAvatarError(){
      this.avatarUploadLoadingDiv.close();
      this.$message({
        message: "照片上传失败,请检查网络",
        type: 'warning'
      });
    },
    init(){

      getAllUserList().then(res => {
        if(res.code == 1) {
          this.userList = res.data;
          // console.log(res.data)
        }
      }).catch(res => {

      });



    },





    isEmpty(val){
      return util.isEmpty(val);
    },

    fmtDate(d2, fmt) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      return  util.fmtDate(new Date(d2), fmt);
    },
    statusDate(data){
      if(data==1){
        return "已完成";
      }else if(data==2){
        return "进行中";
      }else if(data==3){
        return "回退";
      }else if(data==4){
        return "流转";
      }
    },

    productTypeId(productTypeId1,productTypeId2){
      if(productTypeId1=="1"){
        if(productTypeId2==5){
          return "公告/新产品"
        }
        if(productTypeId2==6){
          return "公告/变更扩展"
        }
        if(productTypeId2==7){
          return "公告/整改"
        }
        if(productTypeId2==8){
          return "公告/定型"
        }

      }else if(productTypeId1=="2"){
        if(productTypeId2==9){
          return "达标车型/新产品"
        }
        if(productTypeId2==10){
          return "达标车型/新产品"
        }
        if(productTypeId2==11){
          return "达标车型/新产品"
        }

      }else if(productTypeId1=="3"){
        if(productTypeId2==11){
          return "CCC/新增申请"
        }
        if(productTypeId2==11){
          return "CCC/COP"
        }
        if(productTypeId2==11){
          return "CCC/专项性能"
        }
        if(productTypeId2==11){
          return "CCC/补差"
        }

      }else if(productTypeId1=="4"){
        if(productTypeId2==11){
          return "环保/国环视同"
        }
        if(productTypeId2==11){
          return "环保/北环视同"
        }
        if(productTypeId2==11){
          return "环保/实测"
        }

      }else if(productTypeId1=="19"){
        return "其他/其他"
      }
    },




    showAddForm() {
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.last){
        this.editForm[key] = '';
      }

      this.editForm.carId = this.carId;
      this.editForm.id = 0;
      this.editFormVisible = true;

    },
    computed(){
      this.editForm.totalPrice = this.editForm.price*this.editForm.num

    },
    getUnitPrice(){

      for(var i=0;i<this.TestWorkTypeList.length;i++){
        if(this.TestWorkTypeList[i].name == this.editForm.name){
        this.editForm.price = this.TestWorkTypeList[i].price;
        this.editForm.unit = this.TestWorkTypeList[i].unit;
        }
        this.editForm.totalPrice = this.editForm.price*this.editForm.num
      }
      this.editForm.tOrderId = this.tOrderId;
      this.editForm.costOther = 1;
    },

    handleTaskChangeUser(index, row){
      this.changeUserForm.id = row.id;
      this.changeUserForm.userId = '';

      this.changeUserFormVisible = true;
    },

    submitChangeUser(){

      if(util.isEmpty(this.changeUserForm.userId)){
        this.$message.error("请选择用户");
        return;
      }

      const loadingDiv = util.showLoading("转交中")
      TaskPVchangeUser(this.changeUserForm).then(res => {
        if(res.code == 0) {
          this.$alert(res.msg, "失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(()=> {
              this.changeUserFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },



    handleEdit(index, row) {
      this.editForm.fileVideoList = [];
      this.editForm.fileList = [];
      this.fileList = [];
      this.fileVideoList = [];
    // console.log(editForm.costOther)

      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.editForm){
        this.editForm[key] = row[key];
      }
      this.editFormVisible = true;

      this.editForm.carName = this.editForm.carId

    },
    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {
          this.loading = true;
          let loadingText = "添加中...";
          if(this.editForm.status!=2){
            loadingText = "上传中...";
          }
          const loadingDiv = util.showLoading(loadingText)
          let func = addTestOrderTaskPvList
          if(this.editForm.status!=2){
            func = updateTestOrderTaskPvList
          }
          func(this.editForm).then(res => {
            let title = "添加"
            if(this.editForm.status!=2){
              title = "重新上传"
            }
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(1)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },
    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除："+row.content+"任务?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteTestOrderTaskPvList({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },
    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      getTestOrderTaskPvList({
        pageSize: this.pageSize,
        pageNum: pageNum,
        tOrderId: this.tOrderId,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          let typeArray = [];
          let urlArray = [];
          let news = [];
          this.currentPage = pageNum;
          this.total = data.total;
          this.tableData = data.dataList;
          this.last = data.last;

          for(var i = 0;i<this.tableData.length;i++){
            // console.log("123")
            typeArray=this.tableData[i].fileType.split(",");
            urlArray=this.tableData[i].url.split(",");

            news = []
            for(let j = 0;j<typeArray.length;j++){
              var obj = {};
              obj['type']=typeArray[j];
              obj['url']=urlArray[j];
              news.push(obj)
            }
            this.tableData[i]['news']=(news)
// console.log(this.tableData[i])
          }
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
      // console.log(this.url)
      // console.log(this.url.length)
      // getTestOrderTaskPvFileList()






    },
    search() {
      this.getDataList(1)
    },
    handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
